package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.bean.vo.BaseUserResponse;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.ILoginService;
import com.cskaoyan.user.service.IUserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wjj
 * @date 2023-01-09 20:35
 * @describe
 */
@RestController
@RequestMapping("user")
public class WJJUserController {

    @Autowired
    IKaptchaService kaptchaService;

    @Autowired
    IUserRegisterService userRegisterService;

    @Autowired
    ILoginService loginService;


    @PostMapping("register")
    public BaseUserResponse userRegister(@RequestBody UserRegisterRequest userRegisterRequest, HttpServletRequest request) {
        String captcha = userRegisterRequest.getCaptcha();

        //检验验证码的正确性
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        kaptchaService.validateKaptchaCode(kaptchaCodeRequest);

        //程序运行到这儿说明验证码正确
        //执行插入数据操作
        UserRegisterResponse userRegisterResponse = userRegisterService.register(userRegisterRequest);
        Integer code = userRegisterResponse.getCode();
        String msg = userRegisterResponse.getMsg();
        long currentTimeMillis = System.currentTimeMillis();
        BaseUserResponse<Object> resp = new BaseUserResponse<>();
        resp.setTimestamp(currentTimeMillis);
        resp.setMessage(msg);
        if (code == 401 || code == 402 || code == 403 || code == 404 || code == 405) {
            resp.setResult(null);
            resp.setCode(500);
            resp.setSuccess(false);
        } else {
            resp.setResult(userRegisterResponse);
            resp.setCode(200);
            resp.setSuccess(true);
        }
        return resp;
    }


    @PostMapping("login")
    public BaseUserResponse userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request, HttpServletResponse response) {
        String captcha = userLoginRequest.getCaptcha();

        //检验验证码的正确性
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        kaptchaService.validateKaptchaCode(kaptchaCodeRequest);

        //程序运行到这儿说明验证码正确
        //执行登录校验操作
        UserLoginResponse loginResponse = loginService.login(userLoginRequest);
        BaseUserResponse resp = new BaseUserResponse<>();
        long currentTimeMillis = System.currentTimeMillis();
        if (loginResponse == null) {
            resp.setMessage(UserRetCode.USERORPASSWORD_ERRROR.getMessage());
            resp.setCode(500);
            resp.setResult(null);
            resp.setSuccess(false);
            resp.setTimestamp(currentTimeMillis);
        }else if (UserRetCode.USER_ISEXPIRE_ERROR.getCode().equals(loginResponse.getCode())){
            resp.setMessage(loginResponse.getMsg());
            resp.setCode(500);
            resp.setResult(null);
            resp.setSuccess(false);
            resp.setTimestamp(currentTimeMillis);
        } else{
            Cookie cookie = new Cookie("access_token", loginResponse.getToken());
            cookie.setPath("/");
            response.addCookie(cookie);
            resp.setCode(200);
            resp.setMessage(UserRetCode.SUCCESS.getMessage());
            resp.setSuccess(true);
            resp.setTimestamp(currentTimeMillis);
            resp.setResult(loginResponse);
        }
        return resp;
    }

    @GetMapping("login")
    public BaseUserResponse userLogin(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String token = null;
        for (Cookie cookie : cookies) {
            if ("access_token".equals(cookie.getName())) {
                token = cookie.getValue();
            }
        }
        long currentTimeMillis = System.currentTimeMillis();
        BaseUserResponse resp = new BaseUserResponse();
        if (token != null){
            JwtTokenUtils build = JwtTokenUtils.builder().token(token).build();
            String memberStr = build.freeJwt();

            resp.setCode(200);
            resp.setMessage(UserRetCode.SUCCESS.getMessage());
            resp.setSuccess(true);
            resp.setTimestamp(currentTimeMillis);
            resp.setResult(memberStr);
        }else {
            resp.setMessage(UserRetCode.TOKEN_VALID_FAILED.getMessage());
            resp.setCode(500);
            resp.setResult(null);
            resp.setSuccess(false);
            resp.setTimestamp(currentTimeMillis);
        }
        return resp;
    }

    @GetMapping("loginOut")
    public BaseUserResponse loginOut(HttpServletRequest request,HttpServletResponse resp){
        Cookie[] cookies = request.getCookies();
        String tokenCookieName = "access_token";

        for (int i = 0; i < cookies.length; i++) {
            if (tokenCookieName.equals(cookies[i].getName())){
                cookies[i].setMaxAge(0);
                cookies[i].setPath("/");
                resp.addCookie(cookies[i]);
            }
        }
        BaseUserResponse<Object> response = new BaseUserResponse<>();
        response.setSuccess(true);
        response.setCode(200);
        response.setResult(null);
        response.setMessage("退出成功");
        response.setTimestamp(System.currentTimeMillis());
        return response;
    }
}
